// store.js
import { createStore } from 'vuex'
import api from './api'

export default createStore({
    state: {
        count: 0,
        routesConfig: [],
        userInfo: null,
    },
    mutations: {
        setUserInfo(state, info) {
            state.userInfo = info;
        },
        clearUserInfo(state) {
            state.userInfo = null;
        },
    },
    actions: {
        initializeStore({ commit }) {
            console.log('initializeStore')
            const savedUserInfo = localStorage.getItem('userInfo');
            if (savedUserInfo) {
                commit('setUserInfo', JSON.parse(savedUserInfo));
            }
        },
        updateUserInfo({ commit }, info) {
            console.log('updateUserInfo')
            localStorage.setItem('userInfo', JSON.stringify(info));
            commit('setUserInfo', info);
        },
        async getMenuData({ state }) {
            console.log('updateMenuItems')
            var res = await api.post("RouteConfig/GetAllData")
            state.routesConfig = []
            res.Data.map(x => {
                // 修复组件路径，将 /src/views/ 转换为 ./views/
                let componentPath = x.Component
                if (componentPath && componentPath.startsWith('/src/views/')) {
                    componentPath = componentPath.replace('/src/views/', './views/')
                }
                
                // 特殊处理 RouteConfig 组件的路径问题
                if (componentPath && componentPath.includes('RouteConfig.vue')) {
                    // 确保路径指向正确的目录
                    if (componentPath.includes('./views/RouteConfig.vue')) {
                        componentPath = componentPath.replace('./views/RouteConfig.vue', './views/routeconfig/RouteConfig.vue')
                    }
                }
                
                console.log('Component path:', componentPath) // 调试日志
                
                state.routesConfig.push({
                    path: x.Path,
                    label: x.Label,
                    ...x,
                    component: () => import(componentPath)
                })
            })
            console.log('after map', state.routesConfig)

            return Promise.resolve()

        }
    },
    getters: {
        getUserInfo(state) {
            return state.userInfo;
        },
    },
})